﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
* 项目名称 ：APP.Account.Service
* 项目描述 ：
* 类 名 称 ：CoreService
* 类 描 述 ：
* 所在的域 ：DESKTOP-07DQ4D0
* 命名空间 ：APP.Account.Service
* 机器名称 ：DESKTOP-07DQ4D0 
* CLR 版本 ：4.0.30319.42000
* 作    者 ：Me.笨先生 (66623978)
* 创建时间 ：2018/2/7 10:46:33
* 更新时间 ：2018/2/7 10:46:33
* 版 本 号 ：v1.0.0.0
*******************************************************************
* Copyright @ admin 2018. All rights reserved.
*******************************************************************
//----------------------------------------------------------------*/
#endregion

using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;

using APP.Repository;
using APP.Repository.SqlServer;
using APP.Repository.Extension;

using APP.CommonLib.Log;
using APP.CommonLib.Utils;
using APP.CommonLib.Cache;
using APP.CommonLib.Config;
using APP.CommonLib.XService;
using APP.CommonLib.Extension;

using APP.Basic.Entity;
using APP.Member.Entity;
using APP.Account.Entity;
using APP.Basic.Entity.Response;
using APP.Account.Entity.Entity;
using APP.Account.Entity.Response;
using APP.Repository.Infrastructure.Interception;

namespace APP.Account.Service
{
    /// <summary>
    /// 账户核心操作服务
    /// </summary>
    public class CoreService
    {
        #region 单例实例 Instance
        private static CoreService _instance;
        private static readonly object Lockobj = new object();
        private static readonly MsSqlContext SmsContext = new MsSqlContext(ConfigManager.GetWebConn("sms"));
        private static readonly MsSqlContext BasicContext = new MsSqlContext(ConfigManager.GetWebConn("basic"));

        public static CoreService Instance
        {
            get
            {
                if (_instance != null) return _instance;
                lock (Lockobj)
                {
                    if (_instance == null)
                        _instance = new CoreService();
                }
                return _instance;
            }
        }

        private CoreService()
        {
            /* 添加拦截器，输出 sql 语句极其相应的参数 */
            IDbCommandInterceptor interceptor = new DbCommandInterceptor();
            DbInterception.Add(interceptor);
        }
        #endregion

        /// <summary>
        /// 获取短信验证码
        /// </summary>
        /// <param name="para"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public OperatorStatus GetVcode(GetVCodeParameter para, out string errorMsg)
        {
            try
            {
                string phone;

                //如果号码中有星号，那么通过memberid取出phone
                if (para.Phone.IndexOf("*", StringComparison.Ordinal) > 0)
                {
                    phone = BasicContext.Query<MemberEntity>().Where(m => m.Id == para.MemberId).Select(m => m.Phone).FirstOrDefault();
                    if (string.IsNullOrEmpty(phone))
                    {
                        errorMsg = "token无效";
                        return OperatorStatus.Error;
                    }
                    para.Phone = phone;
                }

                phone = BasicContext.Query<MemberEntity>().Where(m => m.Phone == para.Phone).Select(m => m.Phone).FirstOrDefault();

                switch (para.Type)
                {
                    case SmsType.Regist:
                        if (!string.IsNullOrEmpty(phone))
                        {
                            errorMsg = "此手机号码已被注册";
                            return OperatorStatus.Error;
                        }
                        break;
                    case SmsType.FindLogPwd:
                    case SmsType.FindTradePwd:
                        if (string.IsNullOrEmpty(phone))
                        {
                            errorMsg = "此手机号码还未注册";
                            return OperatorStatus.Error;
                        }
                        break;
                    default:
                        if (string.IsNullOrEmpty(phone))
                        {
                            errorMsg = "此手机号码还未注册";
                            return OperatorStatus.Error;
                        }
                        break;
                }

                var sendCount = SmsContext.Query<SmsMessageEntity>().Where(s => s.Phone == para.Phone && Sql.DiffDays(s.SendTime, DateTime.Now) == 0).Select(a => Sql.Count()).First();
                if (sendCount > 10)
                {
                    errorMsg = "今日短信次数已用完";
                    return OperatorStatus.Error;
                }
                if (!string.IsNullOrEmpty(CacheManager.GetRedisCache(AccountCacheString.VCodeCacheSpace, "VCodeSendCnt" + para.Phone)))
                {
                    errorMsg = "1分钟内只可获取一次";
                    return OperatorStatus.Error;
                }

                //是否测试环境
                var isTestEnv = ConfigManager.GetWebConfig("IsTestEnv", false);

                var code = CacheManager.GetRedisCache(AccountCacheString.VCodeCacheSpace, para.Phone.GetVCodeByPhone());
                if (string.IsNullOrEmpty(code))
                {
                    code = isTestEnv ? "0000" : RandomHelper.GenerateCheckCodeNum(4);
                }

                var p = para.Phone.ToLong();
                var t = para.Type.ToInt();

                CacheManager.PutRedisCache(AccountCacheString.VCodeCacheSpace, para.Phone.GetVCodeByPhone(), code, 60 * 2);
                //发送次数插入Redis
                CacheManager.PutRedisCache(AccountCacheString.VCodeCacheSpace, "VCodeSendCnt" + p, p.ToString() + t, 60);

                SmsContext.Insert(new SmsMessageEntity { Phone = para.Phone, Msg = "您的验证码是：" + code, SendCount = 0, Status = 0, Sign = 0, CreateTime = DateTime.Now });
                BasicContext.Insert(new ValidationCodeEntity { TypeId = t, Phone = p, ValidationCode = code, CreateTime = DateTime.Now, LastUpdateTime = DateTime.Now });

                errorMsg = $"短信发送成功,今日剩余{10 - sendCount}次";
                return OperatorStatus.Success;
            }
            catch (Exception ex)
            {
                Logger.Error("MemberService.GetVCode", ex);
                errorMsg = "短信发送失败";
                return OperatorStatus.Error;
            }
        }

        /// <summary>
        /// 用户注册业务实现
        /// </summary>
        /// <returns></returns>
        public OperatorStatus Regist(RegistParameter para, ServiceRequest req, out string msg)
        {
            try
            {
                msg = "";
                var id = para.Phone.ToLong();
                var isTestEnv = ConfigManager.GetWebConfig("IsTestEnv", false);
                var code = CacheManager.GetRedisCache(AccountCacheString.VCodeCacheSpace, para.Phone.GetVCodeByPhone());
                if (!isTestEnv && (string.IsNullOrEmpty(code) || code != para.VCode))
                {
                    msg = "验证码不正确";
                    return OperatorStatus.Error;
                }

                // 验证 手机是否重复
                var member = BasicContext.Query<MemberEntity>().Where(t => t.IsDelete == 0 && t.Phone == para.Phone).Select(t => t.Phone).FirstOrDefault();
                var memberId = BasicContext.Query<MemberLoginEntity>().Where(t => t.Id == id && t.IsDelete == 0).Select(t => t.MemberId).FirstOrDefault();

                if (member != null || memberId > 0)
                {
                    msg = "此号码已被注册";
                    return OperatorStatus.Error;
                }

                // 使用事务添加用户基本信息
                BasicContext.DoWithTransaction(() =>
                {
                    var insertMember = BasicContext.Insert(new MemberEntity { Phone = para.Phone, HeadPhoto = "", QQ = "", Email = "", WeChat = "", WeChatAuthen = "", ContactName = "", ContactPhone = "", PostCode = "", Address = "", CreateTime = DateTime.Now, LastUpdateTime = DateTime.Now });

                    //设备信息
                    var deviceIdfa = (para.DeviceId + insertMember.Id).ToMD5String().ToLower();
                    BasicContext.Insert(new MemberLoginEntity { Id = para.Phone.ToLong(), MemberId = insertMember.Id, DeviceType = req.platform, LoginPassWord = para.Pswd.ToMD5String().ToLower(), Status = MemberLoginStatus.Ok, DeviceId = para.DeviceId, DeviceInfo = deviceIdfa, CreateTime = DateTime.Now, LoginLastTime = DateTime.Now, LastUpdateTime = DateTime.Now });
                });

                return OperatorStatus.Success;
            }
            catch (Exception e)
            {
                Logger.Error("AccountService.Regist", e);
                msg = "注册失败";
                return OperatorStatus.Error;
            }
        }

        /// <summary>
        /// 填写邀请人
        /// </summary>
        /// <param name="para"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public OperatorStatus InviterFriend(InviterFriendParameter para, out string msg)
        {
            try
            {
                msg = "";

                var member = BasicContext.Query<MemberEntity>().Where(m => m.Id == para.MemberId && m.IsDelete == 0).Select(m => new { m.Id, m.Phone, m.CreateTime }).FirstOrDefault();
                if (string.IsNullOrEmpty(member.Phone))
                {
                    msg = "用户不存在";
                    return OperatorStatus.Error;
                }
                if (para.FriendPhone == member.Phone)
                {
                    msg = "不可以邀请自己哟~~~";
                    return OperatorStatus.Error;
                }

                //是否在有效期内填写邀请人
                var ts = member.CreateTime.Value.Subtract(DateTime.Now).Duration();
                if (ts.Days > 0 || ts.Hours > 24)
                {
                    msg = "已过期了哟~";
                    return OperatorStatus.Error;
                }

                //邀请人信息
                var friend = BasicContext.Query<MemberEntity>().Where(m => m.Phone == para.FriendPhone && m.IsDelete == 0).Select(m => new { m.Phone, m.Id }).FirstOrDefault();
                if (null == friend)
                {
                    msg = "好友还未注册哦,赶快邀请他吧~~~";
                    return OperatorStatus.Error;
                }

                var invites = BasicContext.Query<MemberInviteFriendsEntity>().Where(i => i.FriendId == para.MemberId && i.IsDelete == 0).Select(i => i.Id).FirstOrDefault();
                if (invites == 0)
                {
                    BasicContext.Insert(new MemberInviteFriendsEntity
                    {
                        Phone = friend.Phone,
                        MemberId = friend.Id,
                        FriendPhone = member.Phone,
                        FriendId = member.Id

                        // 重置用户缓存信息

                    });
                }
                else
                {
                    msg = "您已经填写过邀请人了,做人一定要专一哦~~~";
                    return OperatorStatus.Error;
                }


                msg = "您已经填写过邀请人了,做人一定要专一哦~~~";
                return OperatorStatus.Error;
            }
            catch (Exception e)
            {
                Logger.Error("MemberService.SubmitInviter", e);
                msg = "邀请失败";
                return OperatorStatus.Error;
            }
        }

        /// <summary>
        /// 用户登录业务实现
        /// </summary>
        /// <param name="para"></param>
        /// <param name="errorMsg"></param>
        /// <param name="response"></param>
        /// <returns></returns>
        public OperatorStatus Login(LoginParameter para, out string errorMsg, out LoginResponse response)
        {
            errorMsg = "";
            response = new LoginResponse();

            var id = para.Phone.ToLong();
            if (id < 1)
            {
                errorMsg = "账号或密码错误";
                return OperatorStatus.Error;
            }

            try
            {
                // 登录失败次数
                var loginErrorCount = CacheManager.GetRedisCache(AccountCacheString.AccountLoginErrorSpace, para.Phone.GetMemberLoginErrorByPhone()).ToInt();

                if (loginErrorCount >= 5)
                {
                    errorMsg = "登录失败超过5次,请稍后重试";
                    return OperatorStatus.Error;
                }

                // 登录信息
                var pass = para.Pswd.ToMD5String().ToLower();
                var loginInfo = BasicContext.Query<MemberLoginEntity>().Where(m => m.IsDelete == 0 && m.Id == id && m.LoginPassWord == pass).FirstOrDefault();
                if (loginInfo == null)
                {
                    CacheManager.PutRedisCache(AccountCacheString.AccountLoginErrorSpace, para.Phone.GetMemberLoginErrorByPhone(), (loginErrorCount + 1).ToString(), 20 * 100);
                    errorMsg = "账号或密码错误";
                    return OperatorStatus.Error;
                }
                if (MemberLoginStatus.Ok != loginInfo.Status)
                {
                    errorMsg = "此账号已被禁用,请联系客服";
                    return OperatorStatus.Error;
                }

                var deviceList = GetDevices(loginInfo.MemberId);

                // 是否需要短信验证
                int isSmsVerification;

                // 是否设账号保护
                if (loginInfo.IsDevice == 1 && (para.DeviceType == 1 || para.DeviceType == 2))
                {
                    if (deviceList.Count == 0)
                    {
                        isSmsVerification = 1;
                    }
                    else
                    {
                        // 优先设备ID验证，前提条件只是在移动设备上需要校验
                        if (!string.IsNullOrEmpty(para.DeviceId))
                        {
                            isSmsVerification = deviceList.Exists(m => m.DeviceId == para.DeviceId && (para.DeviceType == 1 || para.DeviceType == 2)) ? 0 : 1;
                        }
                        else
                        {
                            isSmsVerification = deviceList.Exists(m => m.DeviceName == para.DeviceName && (para.DeviceType == 1 || para.DeviceType == 2)) ? 0 : 1;
                        }
                    }
                }
                else
                {
                    isSmsVerification = 0;
                }
                response.IsSmsVerification = isSmsVerification;

                //需要短信校验，那么检查VCode是否传入值，如果没有传入，那么直接返回。
                if (response.IsSmsVerification == 1)
                {
                    if (string.IsNullOrEmpty(para.VCode))
                    {
                        return OperatorStatus.Success;
                    }

                    var code = CacheManager.GetRedisCache(AccountCacheString.VCodeCacheSpace, para.Phone.GetVCodeByPhone());
                    if (string.IsNullOrEmpty(code) || code != para.VCode)
                    {
                        errorMsg = "验证码不正确";
                        return OperatorStatus.Error;
                    }
                    //验证通过，那么继续下面的代码逻辑
                    response.IsSmsVerification = 0;
                }

                // 生成token
                var domain = para.Domain;

                if (string.IsNullOrEmpty(domain))
                    domain = "app";
                domain = domain.ToLower();
                var token = PutRedisToken(loginInfo.MemberId, domain, out _);

                // 设备信息
                var deviceIdfa = (para.DeviceId + loginInfo.MemberId).ToMD5String().ToLower();

                var logInfo = BasicContext.Query<MemberLoginLogEntity>().Where(m => m.IsDelete == 0 && m.Id == loginInfo.MemberId).FirstOrDefault();
                if (logInfo == null)
                {
                    logInfo = new MemberLoginLogEntity
                    {
                        Token = string.Empty,
                        WxToken = string.Empty,
                        PcToken = string.Empty,
                        Phone = para.Phone,
                        IP = WebHelper.GetIP(),
                        Id = loginInfo.MemberId,
                        DeviceInfo = deviceIdfa,
                        LoginTime = DateTime.Now,
                        DeviceId = para.DeviceId,
                        CreateTime = DateTime.Now,
                        LastUpdateTime = DateTime.Now,
                        DeviceType = para.DeviceType.ToInt()
                    };
                    switch (domain)
                    {
                        case "app":
                            logInfo.Token = token;
                            break;
                        case "wechat":
                            logInfo.WxToken = token;
                            break;
                        default:
                            logInfo.PcToken = token;
                            break;
                    }
                    BasicContext.Insert(logInfo);
                }
                else
                {
                    logInfo.IP = WebHelper.GetIP();
                    logInfo.DeviceInfo = deviceIdfa;
                    logInfo.LoginTime = DateTime.Now;
                    logInfo.DeviceId = para.DeviceId;
                    logInfo.DeviceType = para.DeviceType.ToInt();
                    logInfo.Token = logInfo.Token ?? string.Empty;
                    logInfo.WxToken = logInfo.WxToken ?? string.Empty;
                    logInfo.PcToken = logInfo.PcToken ?? string.Empty;

                    switch (domain)
                    {
                        case "app":
                            logInfo.Token = token;
                            break;
                        case "wechat":
                            logInfo.WxToken = token;
                            break;
                        default:
                            logInfo.PcToken = token;
                            break;
                    }

                    BasicContext.Update(logInfo);
                }
                response.Token = token;

                //用户设备类型（PC）
                var memberDeviceInfo = BasicContext.Query<MemberDeviceEntity>().Where(d => d.IsDelete == 0 && d.MemberId == loginInfo.MemberId).OrderByDesc(d => d.LastLoginTime).Select(d => new { d.DeviceName, d.LastLoginTime }).FirstOrDefault();

                if (memberDeviceInfo != null)
                {
                    response.DeviceName = memberDeviceInfo.DeviceName;
                    response.LoginLastTime = memberDeviceInfo.LastLoginTime.ToString("yyyy-MM-dd HH:mm:ss");
                }

                response.Member = GetMemberInfoById(loginInfo.MemberId);


                if (domain != "app") return OperatorStatus.Success;
                if (deviceIdfa == response.Member.DeviceInfo) return OperatorStatus.Success;

                response.Member.DeviceInfo = deviceIdfa;
                response.Member.DeviceId = para.DeviceId;

                //更新设备信息
                loginInfo.DeviceInfo = deviceIdfa;
                loginInfo.DeviceId = para.DeviceId;
                loginInfo.CreateTime = DateTime.Now;
                loginInfo.LoginLastTime = DateTime.Now;
                loginInfo.LastUpdateTime = DateTime.Now;
                BasicContext.Update(loginInfo);

                return OperatorStatus.Success;
            }
            catch (Exception ex)
            {
                Logger.Error("AccountService.Login", ex);
                errorMsg = "登录超时";
                return OperatorStatus.Error;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="memberId"></param>
        /// <returns></returns>
        public List<MemberDevice> GetDevices(long memberId)
        {
            var list = BasicContext.Query<MemberDeviceEntity>().Where(m => m.IsDelete == 0 && m.MemberId == memberId).ToList();
            var listDevice = (from a in list
                              select new MemberDevice
                              {
                                  DeviceId = a.DeviceId,
                                  DeviceName = a.DeviceName,
                                  DeviceModel = a.DeviceModel,
                                  DeviceType = a.DeviceType,
                                  LastLoginTimeStr = a.LastLoginTime.ToString("yyyy-MM-dd HH:mm:ss")
                              }).OrderByDescending(m => m.LastLoginTimeStr).ToList();

            foreach (var device in listDevice)
            {
                if (string.IsNullOrEmpty(device.DeviceName))
                {
                    device.DeviceName = "未知设备";
                }
                if (string.IsNullOrEmpty(device.DeviceModel))
                {
                    device.DeviceModel = "未知型号";
                }
            }
            return listDevice;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="memberId"></param>
        /// <param name="domain"></param>
        /// <param name="lastToken"></param>
        /// <returns></returns>
        private static string PutRedisToken(long memberId, string domain, out string lastToken)
        {
            //缓存失效时间（30天）
            var cacheTime = ConfigManager.GetWebConfig("LoginKeepAlive@" + domain, 86400 * 30);

            //生成token
            var token = (memberId + DateTime.Now.ToUnixStr().ToString() + "@" + domain).ToMD5String().ToLower() + "@" + domain;

            lastToken = CacheManager.GetRedisCache(AccountCacheString.AccountTokenCacheSpace, memberId.GetMemberTokenInfoById(domain));
            if (string.IsNullOrEmpty(lastToken))
            {
                CacheManager.PutRedisCache(AccountCacheString.AccountTokenCacheSpace, memberId.GetMemberTokenInfoById(domain), token, cacheTime);
                CacheManager.PutRedisCache(AccountCacheString.AccountTokenCacheSpace, token, memberId.ToString(), cacheTime);
            }
            else
            {
                CacheManager.DelRedisCache(AccountCacheString.AccountTokenCacheSpace, lastToken);
                CacheManager.PutRedisCache(AccountCacheString.AccountTokenCacheSpace, memberId.GetMemberTokenInfoById(domain), token, cacheTime);
                CacheManager.PutRedisCache(AccountCacheString.AccountTokenCacheSpace, token, memberId.ToString(), cacheTime);
            }
            return token;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="memberId"></param>
        /// <param name="isCache"></param>
        /// <param name="isWriteCache"></param>
        /// <returns></returns>
        public MemberInfoResponse GetMemberInfoById(long memberId, bool isCache = true, bool isWriteCache = true)
        {
            //是否缓存
            if (isCache)
            {
                var memberInfoStr = CacheManager.GetRedisCache(AccountCacheString.AccountInfoCacheSpace, memberId.GetMemberInfoById());
                if (!string.IsNullOrEmpty(memberInfoStr))
                {
                    return JsonHelper.JsonDeserialize<MemberInfoResponse>(memberInfoStr);
                }
            }

            try
            {
                var model = new MemberInfoResponse();

                var basicEntity = BasicContext.Query<MemberEntity>().Where(m => m.IsDelete == 0 && m.Id == memberId).FirstOrDefault();
                if (null == basicEntity)
                    return null;

                model.Phone = basicEntity.Phone;
                if (!string.IsNullOrEmpty(model.Phone))
                {
                    model.Phone = CommonUtils.MaskString(model.Phone, '*', 4, model.Phone.Length - 7);
                }
                model.HeadPhoto = basicEntity.HeadPhoto ?? "";
                model.RealNameAuthen = basicEntity.RealNameAuthen ?? 0;
                model.BankCardAuthen = basicEntity.BankCardAuthen ?? 0;

                //地址信息
                model.ContactBoy = basicEntity.ContactName ?? "";
                model.ContactPhone = basicEntity.ContactPhone ?? "";
                model.ZipCode = basicEntity.PostCode ?? "";
                model.Address = basicEntity.Address ?? "";

                //是否购买
                model.IsBuy = basicEntity.IsBuy ?? 0;

                var authenEntity = BasicContext.Query<MemberAuthenEntity>().Where(m => m.IsDelete == 0 && m.MemberId == memberId).FirstOrDefault();
                if (null != authenEntity)
                {
                    model.BankPhone = !string.IsNullOrEmpty(authenEntity.BankPhone) ? authenEntity.BankPhone : basicEntity.Phone;
                    if (!string.IsNullOrEmpty(model.BankPhone) && model.BankPhone.Length > 10)
                    {
                        model.BankPhone = CommonUtils.MaskString(model.BankPhone, '*', 4, 4);
                    }
                    if (!string.IsNullOrEmpty(authenEntity.RealName))
                    {
                        model.RealName = authenEntity.RealName;
                    }

                    if (!string.IsNullOrEmpty(authenEntity.CardId))
                    {
                        model.CardId = authenEntity.CardId;
                    }

                    model.BankCardId = authenEntity.BankCardId ?? "";
                    if (!string.IsNullOrEmpty(model.BankCardId))
                    {
                        model.BankCardId = "尾号(" + model.BankCardId.Substring(model.BankCardId.Length - 4) + ")";
                    }
                    model.OpenAccountName = authenEntity.OpenAccountName ?? "";
                    var banks = GetAllBanks();
                    var bank = banks.FirstOrDefault(it => it.Id == authenEntity.BankId);
                    if (bank != null)
                    {
                        model.BankName = bank.BankName;
                        model.BankIcon = bank.BankIcon;
                        model.SinglePrice = bank.SinglePrice;
                        model.DayPrice = bank.DayPrice;
                        model.PayCode = bank.BankCode;
                        model.BankSysId = bank.Id;
                    }
                }

                //邀请人信息
                var friendPhone = BasicContext.Query<MemberInviteFriendsEntity>().Where(f => f.IsDelete == 0 && f.FriendId == memberId).Select(f => f.Phone).FirstOrDefault();

                if (!string.IsNullOrEmpty(friendPhone))
                {
                    //如果存在邀请人 状态设置为1
                    model.FriendStatus = 1;
                    model.FriendPhone = CommonUtils.MaskString(friendPhone, '*', 4, 4);
                }
                else
                {
                    if (basicEntity.CreateTime != null)
                    {
                        var ts = basicEntity.CreateTime.Value.Subtract(DateTime.Now).Duration();
                        if (ts.Days > 0 || ts.Hours > 24)
                            model.FriendStatus = 1;
                        else
                            model.FriendStatus = 0;
                    }

                    model.FriendPhone = "";
                }

                //设备信息
                var login = BasicContext.Query<MemberLoginEntity>(t => t.IsDelete == 0 && t.MemberId == memberId).Select(t => new { t.DeviceId, t.IsDevice, t.DeviceInfo }).FirstOrDefault();
                if (null != login)
                {
                    model.DeviceId = login.DeviceId;
                    model.DeviceInfo = login.DeviceInfo;
                    model.IsDevice = login.IsDevice;
                }

                //存入Cache
                if (model.Phone.Length <= 1 || !isWriteCache) return model;

                var modelStr = JsonHelper.JsonSerializer(model);
                if (!string.IsNullOrEmpty(modelStr))
                {
                    Task.Run(() =>
                    {
                        CacheManager.PutRedisCache(AccountCacheString.AccountInfoCacheSpace, memberId.GetMemberInfoById(), modelStr, 60 * 5);
                    });
                }
                return model;
            }
            catch (Exception e)
            {
                Logger.Error("AccountService.GetMemberInfo", e);
                return null;
            }
        }

        /// <summary>
        /// 获取所有的银行
        /// </summary>
        /// <returns></returns>
        public List<BankInfoResponse> GetAllBanks()
        {
            var bankStr = CacheManager.GetRedisCache("BasicCache", "BankAll");
            if (!string.IsNullOrEmpty(bankStr)) return JsonHelper.JsonDeserialize<List<BankInfoResponse>>(bankStr);

            var banks = BasicContext.Query<BankEntity>().Where(b => b.IsDelete == 0 && b.IsUse == 1)
                .Select(b => new BankInfoResponse
                {
                    Id = b.Id,
                    BankCode = b.BankCode,
                    BankIcon = b.BankIcon,
                    BankName = b.BankName,
                    Code = b.Code,
                    DayPrice = GetPriceText(b.DayPrice),
                    SinglePrice = GetPriceText(b.SinglePrice),
                    MonthPrice = GetPriceText(b.MonthPrice)
                }).ToList();

            bankStr = JsonHelper.JsonSerializer(banks);
            CacheManager.PutRedisCache("BasicCache", "BankAll", bankStr, 24 * 60 * 60);

            return JsonHelper.JsonDeserialize<List<BankInfoResponse>>(bankStr);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="price"></param>
        /// <returns></returns>
        public static string GetPriceText(decimal price)
        {
            var res = price.ToString();
            try
            {
                price = (int)price;
                if (price > 0)
                {
                    var num = price / 1000;
                    if (num < 10)
                        res = price.ToString();
                    else if (num >= 10)
                        res = price / 10000 + "万";
                }
                else if (price == 0)
                {
                    res = "0元";
                }
                else if (price < 0)
                {
                    res = "无限制";
                }
                return res;
            }
            catch (Exception ex)
            {
                Logger.Error("AccountService.GetPriceText", ex.Message);
                return res;
            }
        }
    }
}